package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Region;
import cn.wolfcode.luowowo.article.mapper.DestinationMapper;
import cn.wolfcode.luowowo.article.mapper.RegionMapper;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.common.query.DestinationQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DestinationServiceImpl implements IDestinationService {
    @Autowired
    private DestinationMapper destinationMapper;
    @Autowired
    private RegionMapper regionMapper;


    public PageInfo query(DestinationQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Destination> list = destinationMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public void setInfo(Destination destination) {
        destinationMapper.updateByPrimaryKey(destination);
    }

    public List<Destination> listToasts(Long parentId) {
        List<Destination> list = new ArrayList<>();
        Destination dest = destinationMapper.selectByPrimaryKey(parentId);
        list.add(dest);//添加当前目的地

        while (dest.getParent() != null) {//如果当前目的地有父级
            dest = destinationMapper.selectByPrimaryKey(dest.getParent().getId());
            list.add(dest);//添加父级目的地 >>
        }
        //逆序
        Collections.reverse(list);
        return list;
    }

    public void changeHotState(Long id, Integer hot) {
        destinationMapper.updateHotState(id, hot);
    }

    public List<Destination> listDestByRegionId(Long rid) {

        Region region = regionMapper.selectByPrimaryKey(rid);
        Long[] refIds = region.getRefIds();

        List<Destination> destinations = destinationMapper.selectDestByRIds(refIds);
        return destinations;
    }

    public List<Destination> listDests() {
        return destinationMapper.selectDests();
    }

    public List<Destination> listHotDestByRegionId(Long regionId) {
        List<Destination> destinations = destinationMapper.listHotDestByRegionId(regionId);//查询出当前区域下的目的地
        return destinations;
    }

    public Destination getCountry(Long destId) {
        List<Destination> toasts = listToasts(destId);
        return toasts.get(0);
    }

    public Destination getProvince(Long destId) {
        List<Destination> toasts = listToasts(destId);
        return toasts.size() > 1 ? toasts.get(1) : null;
    }

    public List<Destination> list() {
        return destinationMapper.selectAll();
    }

}
